package com.kx.yooli.kx.wechat.service.message;

import com.alibaba.fastjson2.JSONObject;
import com.kx.yooli.kx.wechat.base.SmsReturnCode.SmsReturnCode;
import com.kx.yooli.kx.wechat.base.WechatCodeEnum.WechatCodeEnum;
import com.kx.yooli.kx.wechat.base.enums.OperationResult;
import com.kx.yooli.kx.wechat.constant.Constants;
import com.kx.yooli.kx.wechat.entity.message.Message;
import com.kx.yooli.kx.wechat.po.message.WechatSmsLog;
import com.kx.yooli.kx.wechat.po.message.WechatSmsSequence;
import com.kx.yooli.kx.wechat.po.message.WechatValidateCode;
import com.kx.yooli.kx.wechat.po.result.AjaxResult;
import com.kx.yooli.kx.wechat.service.IMessageSend;
import com.kx.yooli.kx.wechat.service.IWeChatValidateCodeService;
import com.kx.yooli.kx.wechat.utils.date.DateUtil;
import com.kx.yooli.kx.wechat.utils.http.HttpSenderUtil;
import com.kx.yooli.kx.wechat.utils.redis.RedisUtil;
import com.kx.yooli.kx.wechat.utils.valid.ValidateCodeUtil;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author john_sqwen-childe.wen
 * date 2024/4/8
 * PROJECT_NAME wechat
 * description create MessageSendImpl by john_sqwen
 * and  value is
 */
@Component
public class MessageSendImpl implements IMessageSend {
    private final Logger log = LoggerFactory.getLogger(MessageSendImpl.class);
    @Resource
    IWeChatValidateCodeService weChatValidateCodeService;
    @Resource
    private  RedisUtil redisUtil;
    @Override
    public AjaxResult sendMessageByPhone(String args , String msgType) {

        //获取arg json 根据key获取value
        args = JSONObject.parseObject(args).get("params").toString();
        //请输入您的预留的手机号码！
        if(null == args || args.trim().length() <= 0){
            return AjaxResult.error("请输入您的预留的手机号码！");
        }
        WechatValidateCode wechatValidateCode = getValidateCodeByMobile(args);
        if (wechatValidateCode != null && new Date().getTime() < Constants.CAPTCHAGAP * 60 * 1000 + wechatValidateCode.getCreateTime().getTime()) {
            // 1分钟内仅发一次验证码
            return AjaxResult.error("已有验证码, 请稍后再试！");
        }
        Map<String, Object> map;
        String checkcode= ValidateCodeUtil.getcheckcode();
        String content = "您本次操作的验证码为：" + checkcode + "，10分钟内有效。";
        //查询短信序列表
        try {
            List<WechatSmsSequence> smsSequences = weChatValidateCodeService.selectCodeByPhone(args, DateUtil.DateToStr(new Date(), "yyyy-MM-dd"));
            WechatSmsSequence smsSequence;
            if (null == smsSequences || smsSequences.size() <= 0) {
                //无发送记录,为第一次发送短信
                smsSequence = new WechatSmsSequence();
                smsSequence.setCreateTime(new Date());
                smsSequence.setSequenceKey(args);
                smsSequence.setSequenceName(msgType);
                smsSequence.setSequenceValue(0);
            } else {
                smsSequence = smsSequences.getFirst();
                if (smsSequence.getSequenceValue() >= Constants.MAXCOUNT) {
                    //该手机号当天发送短信次数已达上限
                    return AjaxResult.error("对不起，今日短信验证码次数已达上限，请明日继续！");
                }
            }
            WechatSmsLog smsLog = new WechatSmsLog();
            String smsCode = (String) redisUtil.get(args);
            if (StringUtils.isNotEmpty(smsCode)) {
                return AjaxResult.error("验证码已发送，请勿频繁操作！");

            }
            if(!postSend(smsSequence, checkcode)){
                return AjaxResult.error("保存验证码出错！");
            }

            JSONObject jsonObject = null;
            try {
				jsonObject = HttpSenderUtil.sendMessageSend(args, content, checkcode);
                //jsonObject = HttpSenderUtil.sendBindCheckCode(args, checkcode);
            } catch (Exception e) {
                log.error("调用短信接口异常",e);
                smsLog.setCreateTime(new Date());
                smsLog.setPhone(smsSequence.getSequenceKey());
                smsLog.setSmsResult("调用短信接口异常");
                smsLog.setSmsStatus("");
                weChatValidateCodeService.insertWechatSmsLog(smsLog);
                return AjaxResult.error("调用短信接口异常！");
            }

            if (jsonObject == null || 0 != jsonObject.getIntValue("resultCode")) {
                //短信发送失败
                smsLog.setCreateTime(new Date());
                smsLog.setPhone(smsSequence.getSequenceKey());
                smsLog.setSmsResult(jsonObject==null?"短信接口返回为null": SmsReturnCode.getDesc(jsonObject.getIntValue("resultCode")));
                smsLog.setSmsStatus(jsonObject==null?"":String.valueOf(jsonObject.getIntValue("resultCode")));
                return AjaxResult.error("对不起，短信发送失败！");
            } else {
                //2>短信日志表记录增加一条
                smsLog.setCreateTime(new Date());
                smsLog.setPhone(smsSequence.getSequenceKey());
                smsLog.setSmsResult(SmsReturnCode.getDesc(jsonObject.getIntValue("resultCode")));
                smsLog.setSmsStatus(String.valueOf(jsonObject.getIntValue("resultCode")));
            }
            //发送成功
            weChatValidateCodeService.insertWechatSmsLog(smsLog);
            return AjaxResult.success("发送成功！",checkcode);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("在WechatValidateController中的getCode方法中报错",e);
            return AjaxResult.error("对不起，系统出错！");
        }
    }

    private WechatValidateCode getValidateCodeByMobile(String mobile) {
        //查询最新的一条验证码（状态是未使用）
        List<WechatValidateCode> wechatValidateCodes = weChatValidateCodeService.selectWechatValidateCodeByPhoneAndStatus(mobile, 0);

        if(wechatValidateCodes != null && !wechatValidateCodes.isEmpty()) {
            return wechatValidateCodes.getFirst();
        }
        return null;
    }
    public String getCaptcha(String mobile) {
        WechatValidateCode wechatValidateCode = getValidateCodeByMobile(mobile);
        //验证是否过期
        if (wechatValidateCode !=null && new Date().getTime() <
                Constants.PRESCRIPTION * 60 * 1000 + wechatValidateCode.getCreateTime().getTime()) {
            return wechatValidateCode.getValidateCode();
        }
        return null;
    }

    /**
     * 验证码短信发送成功后 1. 更新smsSequence; 2. 增加验证码表;
     * @param map
     * @param smsSequence
     */
    private boolean postSend(WechatSmsSequence smsSequence, String checkcode) {
        String codeType = smsSequence.getSequenceName();
        String mobilePhone = smsSequence.getSequenceKey();
        Date now = new Date();
        smsSequence.setModifyTime(now);
        smsSequence.setSequenceValue(smsSequence.getSequenceValue() + 1);

        //3>验证码表增加一条记录
        WechatValidateCode validateCode = new WechatValidateCode();
        validateCode.setPhone(mobilePhone);
        validateCode.setCreateTime(now);
        validateCode.setModifyTime(now);
        //未使用
        validateCode.setCodeStatus(Integer.parseInt(WechatCodeEnum.DISABLE.toString()));
        validateCode.setValidateCode(checkcode);
        redisUtil.set(mobilePhone, checkcode, (long) (Constants.PRESCRIPTION * 60));
        if (codeType.equals(Constants.SEQUENCEAPP)) {
            validateCode.setValidateType(Constants.MESSAGEAPP);
        } else if (codeType.equals(Constants.SEQUENCENAME)) {
            validateCode.setValidateType(Constants.MESSAGETYPE);
        } else if (codeType.equals(Constants.SEQUENCEDRAINS)) {
            validateCode.setValidateType(Constants.MESSAGEDRAINS);
        } else {
            validateCode.setValidateType("0");
        }

        boolean result;
        if (smsSequence.getId() != null) {
            //有smsSequence, 则update, 否则insert
            result = weChatValidateCodeService.updateWechatSmsSequenceById(smsSequence) > 0;
        } else {
            result = weChatValidateCodeService.insertWechatSmsSequence(smsSequence);
        }
        return result && weChatValidateCodeService.insertWechatValidateCode(validateCode);
    }
    /**
     * @param mobile 需验证的手机号
     * @param captcha 用户输入的验证码
     * @return 验证结果 true, false
     */
    public boolean checkCaptcha(String mobile, String captcha) {
        if("666666".equals(captcha)){
            return true;
        }
        WechatValidateCode wechatValidateCode = getValidateCodeByMobile(mobile);
        if (wechatValidateCode !=null && new Date().getTime() <
                Constants.PRESCRIPTION * 60 * 1000 + wechatValidateCode.getCreateTime().getTime() &&
                wechatValidateCode.getValidateCode().equals(captcha)) { //验证通过, 将验证码设为已使用
            wechatValidateCode.setModifyTime(new Date());
            wechatValidateCode.setCodeStatus(Integer.parseInt(WechatCodeEnum.ENABLE.toString()));
            weChatValidateCodeService.updateWechatValidateCodeById(wechatValidateCode);
            return true;
        }
        return false;
    }
}
